<template>
    <div>
        <BaseForm ref="searchForm" type="search" v-model:items="formItems" v-model:form="searchParams"
            @search="handleSearch" labelWidth="120px">
            <el-form-item>
                <el-radio-group v-model="dateRadio" @change="dateChange">
                    <el-radio-button label="今日" />
                    <el-radio-button label="昨日" />
                    <el-radio-button label="本周" />
                    <el-radio-button label="本月" />
                    <el-radio-button label="今年" />
                    <el-radio-button label="全部" />
                    <el-radio-button label="自定义" />
                </el-radio-group>
            </el-form-item>
            <el-form-item>
                <el-date-picker style="width: 330px" v-model="searchParams.date" type="datetimerange"
                    :disabled="disabledTime"  range-separator="~" value-format="YYYY-MM-DD HH:ss:mm"
                    start-placeholder="开始时间" end-placeholder="结束时间" :default-time="[
                        new Date(0, 0, 0, 0, 0, 0),
                        new Date(0, 0, 0, 23, 59, 59),
                    ]" />
            </el-form-item>
            <el-form-item label="微信名称">
                <el-input style="width: 255px" v-model="searchParams.wxUserName" placeholder="请输入"></el-input>
            </el-form-item>
<!--            <el-form-item label="供电单位">-->
<!--                <el-select style="width: 255px" v-model="searchParams.powerId" filterable placeholder="请选择"-->
<!--                    @change="changePower" clearable>-->
<!--                    <el-option v-for="item in powerSupplyIdList" :key="item.value" :value="item.value" :label="item.label">-->
<!--                    </el-option>-->
<!--                </el-select>-->
<!--            </el-form-item>-->
<!--            <el-form-item label="供电线路" style="margin-left: 30px;">-->
<!--                <el-select style="width: 255px;" v-model="searchParams.lineId" filterable placeholder="请选择" clearable>-->
<!--                    <el-option v-for="item in lineIdList" :key="item.value" :value="item.value" :label="item.label">-->
<!--                    </el-option>-->
<!--                </el-select>-->
<!--            </el-form-item>-->

          <el-form-item label="供电单位">
            <selectPage
                style="width: 180px"
                :item="powerItem"
                v-model="searchParams.powerId"
                @update:modelValue="changePower"
            />
          </el-form-item>
          <el-form-item label="供电线路">
            <selectPage
                :item="lineItem"
                v-model="searchParams.lineId"
                :search="searchParams.lineSearch"
                @update:modelValue="changeLine"
            />
          </el-form-item>

            <el-form-item label="台区">
              <selectPage
                  :item="areaItem"
                  v-model="searchParams.areaId"
                  :search="searchParams.areaSearch"
                  @update:modelValue="changeArea"
              />
            </el-form-item>

            <el-form-item label="关联片区/村社">
              <selectPage
                  :item="communityItem"
                  ref="CommunityRef"
                  v-model="searchParams.communityId"
                  :search="searchParams.communitySearch"
              />

<!--                <el-select style="width: 255px" v-model="searchParams.communityId" filterable placeholder="请选择" clearable>-->
<!--                    <el-option v-for="item in communityList" :key="item.value" :value="item.value" :label="item.label">-->
<!--                    </el-option>-->
<!--                </el-select>-->
            </el-form-item>
            <el-form-item label="关联网格经理">
                <el-select style="width: 255px" v-model="searchParams.managerId" filterable placeholder="请选择" clearable>
                    <el-option v-for="item in optionsMange" :key="item.value" :value="item.value" :label="item.label">
                    </el-option>
                </el-select>
            </el-form-item>

        </BaseForm>

        <BaseTable ref="baseTable" :getTableDataFn="reportStatisticsService.opinionKeyRecordPageList"
            :searchParams="searchParams" :downLoad="downLoad" :serial="true" :down="true" serialLabel="触发次数排名">
            <el-table-column prop="typeName" label="舆情分类" />
            <el-table-column prop="opinionKey" label="舆情关键词" />
            <el-table-column prop="totalNum" label="触发次数">
                <template #header>
                    <span>触发次数</span>
                    <SortTable :type="1" :sortTablekey="sortTablekey" @click="handleSort(1)"
                        v-model:searchParams="searchParams" :handleSearch="handleSearch"></SortTable>
                </template>
            </el-table-column>
            <el-table-column prop="groupNum" label="触发群聊数">
                <template #header>
                    <span>触发群聊数</span>
                    <SortTable :type="2" :sortTablekey="sortTablekey" @click="handleSort(2)"
                        v-model:searchParams="searchParams" :handleSearch="handleSearch"></SortTable>
                </template>
                <template #default="scope">
                    <el-link :underline="false" link type="primary" size="small"
                        @click.prevent="openGroupChat(scope.row)">{{ scope.row.groupNum }}</el-link>
                </template>
            </el-table-column>

            <el-table-column prop="userNum" label="触发客户数">
                <template #default="scope">
                    <el-link :underline="false" link type="primary" size="small"
                        @click.prevent="openGroupChat(scope.row)">{{ scope.row.userNum }}</el-link>
                </template>
            </el-table-column>
            <el-table-column prop="communityNum" label="相关片区/村社数">
                <template #default="scope">
                    <el-link :underline="false" link type="primary" size="small"
                        @click.prevent="openGroupChat(scope.row)">{{ scope.row.communityNum }}</el-link>
                </template>
            </el-table-column>
        </BaseTable>

    </div>
</template>
  
<script setup lang="ts">
import SortTable from '@/components/sortTable.vue'
import { basicConfigService } from '@/api/basicConfig'
import { reportStatisticsService } from '@/api/reportStatistics'
import { commonService } from '@/api/common'
import { powerService } from '@/api/power'
import { lineService } from '@/api/line'
const lineIdList = ref([])
const powerSupplyIdList = ref([])
const cateList = ref([])
import moment from 'moment'
const dateRadio = ref('今日')
const item = ref({})
const visibleGroupChat = ref(false)
const dateChange = (val) => {
    switch (val) {
        case '今日':
            searchParams.value.recordTimeBegin = moment().format(
                'yyyy-MM-DD 00:00:00'
            )
            searchParams.value.recordTimeEnd = moment().format('yyyy-MM-DD 23:59:59')
            break
        case '昨日':
            searchParams.value.recordTimeBegin = moment()
                .subtract(1, 'days')
                .format('yyyy-MM-DD 00:00:00')
            searchParams.value.recordTimeEnd = moment()
                .subtract(1, 'days')
                .format('yyyy-MM-DD 23:59:59')
            break
        case '本周':
            searchParams.value.recordTimeBegin = moment()
                .weekday(1)
                .format('yyyy-MM-DD 00:00:00')
            searchParams.value.recordTimeEnd = moment().format('yyyy-MM-DD 23:59:59')
            break
        case '本月':
            searchParams.value.recordTimeBegin = moment().format(
                'yyyy-MM-01 00:00:00'
            )
            searchParams.value.recordTimeEnd = moment().format('yyyy-MM-DD 23:59:59')
            break
        case '今年':
            searchParams.value.recordTimeBegin = moment().format(
                'yyyy-01-01 00:00:00'
            )
            searchParams.value.recordTimeEnd = moment().format('yyyy-MM-DD 23:59:59')
            break
        case '全部':
            searchParams.value.recordTimeBegin = undefined
            searchParams.value.recordTimeEnd = undefined
            break
        default:
            return
    }
    handleSearch()
}
const sortTablekey = ref(0)
const isDesc = ref(null)
const handleSort = (e) => {
    sortTablekey.value = e
}
const disabledTime= computed(() => dateRadio.value !== '自定义')
const formItems = ref([
    /*  {
         name: '',
         key: 'date',
         type: 'datetimerange',
         placeholder: '选择时间范围',
         disabled: computed(() => dateRadio.value !== '自定义'),
     },
 
     {
         name: '微信名称',
         key: 'opinionKey',
         clearable: true,
         type: 'input',
     }, */
])
const searchParams = ref({
    typeId: '',
    opinionKey: '',
    recordTimeBegin: moment().format('yyyy-MM-DD 00:00:00'),
    recordTimeEnd: moment().format('yyyy-MM-DD 23:59:59'),
    date: [],

    powerId: '',
    lineId: '',
    areaId: '',
    communityId:'',
    managerId:'',
    wxUserName:'',


    //临时变量
    lineSearch:{
      powerId:"",
    },
    areaSearch:{
      powerId:"",
      lineId:""
    },
    communitySearch:{
      powerId:"",
      lineId:"",
      areaId:"",
    }
})

const baseTable = ref(null)
const handleSearch = (data = { sort: undefined }, e = '') => {
    if (e != 'sort') sortTablekey.value = 0
    if (data) isDesc.value = data.sort
    else {
        isDesc.value = null
    }
    if (data == null) {
        dateRadio.value = '今日'
        searchParams.value.typeId = ''
    }
    const date = searchParams.value.date
    if (dateRadio.value === '自定义') {
        searchParams.value.recordTimeBegin = date[0] || undefined
        searchParams.value.recordTimeEnd = date[1] || undefined
    } else {
        searchParams.value.date = []
    }
    setTimeout(() => {
        baseTable.value.handleSearch({
            ...searchParams.value,
            orderField: sortTablekey.value,
            isDesc: data?.sort,
            date: undefined,
        })
    })
}
const downLoad = () => {
  reportStatisticsService
      .opinionKeyRecordPageListDownload({
        data: {
          ...searchParams.value,
          orderField: sortTablekey.value,
          isDesc: isDesc.value,
          date: undefined,
        },
      })
      .then((res) => {
        var blob = new Blob([res]);
        let url = window.URL.createObjectURL(blob);
        let link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', '诉求回复统计.xls');
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      });
}
const getListByParentKey = () => {
    commonService
        .getListByParentKey({ data: 'cruxKeyManager' })
        .then((res) => {
            let data = res.data.map((e) => {
                return {
                    label: e.dictionaryName,
                    value: e.dictionaryValue,
                }
            })
            cateList.value.push(...data)
        })
}
const openGroupChat = (row) => {
    item.value = { ...row }
    visibleGroupChat.value = true
}
const communityList = ref([])
const getAllCommunity = () => {
    basicConfigService.getAllCommunity({ data: {} }).then((res) => {
        let data = res.data.map((e) => {
            return {
                label: e.communityName,
                value: e.communityId,
            }
        })
        communityList.value.push(...data)
    })
}
const getPowerList = () => {
    powerService.getPowerList({ data: {} }).then((res) => {
        powerSupplyIdList.value = res.data.map((n) => {
            return {
                label: n.powerName,
                value: n.powerId,
            }
        })
    })
}
const getLineList = () => {
    lineService
        .getLineList({ data: { powerId: searchParams.value.powerId } })
        .then((res) => {
            lineIdList.value = res.data.map((n) => {
                return {
                    label: n.lineName,
                    value: n.lineId,
                }
            })
        })
}

const powerItem = ref({
  name: '供电单位',
  key: 'powerId',
  funName: 'getByAreaQueryByPower',
  option: {
    name: 'powerName',
    value: 'powerId',
  },
});

const lineItem = ref({
  name: '供电线路',
  key: 'lineId',
  funName: 'getByAreaQueryByLine',
  option: {
    name: 'lineName',
    value: 'lineId',
  },
});

const areaItem = ref({
  name: '台区',
  key: 'areaId',
  funName: 'getByAreaQueryByArea',
  option: {
    name: 'areaName',
    value: 'areaId',
  },
});


const communityItem = ref({
  name: '关联片区/村社',
  key: 'communityId',
  funName: 'getAllCommunity',
  option: {
    name: 'communityName',
    value: 'communityId',
  },
});

const changePower = (val: any) => {
  //线路搜索
  searchParams.value.lineSearch.powerId = val;
  //台区搜索赋值
  searchParams.value.areaSearch.powerId = val;
  searchParams.value.areaSearch.lineId ="";

  //社区搜索赋值
  searchParams.value.communitySearch.powerId = val;
  searchParams.value.communitySearch.lineId = "";
  searchParams.value.communitySearch.areaId = "";

  //公共搜索
  searchParams.value.lineId = '';
  searchParams.value.areaId = '';
  searchParams.value.communityId = '';
};
const changeLine = (val: any) => {
  searchParams.value.areaSearch.lineId = val;

  searchParams.value.communitySearch.lineId = val;
  searchParams.value.communitySearch.areaId = '';

  searchParams.value.areaId = '';
  searchParams.value.communityId = '';
};

const changeArea = (val: any) => {
  searchParams.value.communitySearch.areaId = val;

  searchParams.value.communityId = '';
};


const optionsMange = ref([])
const getAllManager = () => {
    basicConfigService.getAllManager({ data: {} }).then((res) => {
        optionsMange.value = res.data.map((n) => {
            return {
                label: n.managerName,
                value: n.managerId,
            }
        })
    })
}
// const changePower = () => {
//     if (searchParams.value.powerId) {
//         searchParams.value.lineId = ''
//     }
//     getLineList()
// }

onMounted(() => {
    getListByParentKey()
    getPowerList()
    getLineList()
    getAllManager();
    getAllCommunity();
})
</script>
  
<style lang="scss" scoped>
:deep(.el-date-editor) {
    padding: 1px 10px;
}
</style>
  